import os
import pandas as pd
from pyecharts.charts import Bar
from pyecharts import options as opts
import webbrowser

# 所有区文件路径
folder = "data/"
files = [
    "北京昌平天气_2015_2025.xlsx", "北京朝阳天气_2015_2025.xlsx", "北京大兴天气_2015_2025.xlsx",
    "北京东城天气_2015_2025.xlsx", "北京房山天气_2015_2025.xlsx", "北京丰台天气_2015_2025.xlsx",
    "北京海淀天气_2015_2025.xlsx", "北京怀柔天气_2015_2025.xlsx", "北京门头沟天气_2015_2025.xlsx",
    "北京平谷天气_2015_2025.xlsx", "北京石景山天气_2015_2025.xlsx", "北京顺义天气_2015_2025.xlsx",
    "北京通州天气_2015_2025.xlsx", "北京西城天气_2015_2025.xlsx", "北京延庆天气_2015_2025.xlsx",
    "新北京密云天气_2015_2025.xlsx"
]

districts = [f.split("天气")[0].replace("新北京", "北京") for f in files]
summer_avg = []
winter_avg = []

for file in files:
    full_path = os.path.join(folder, file)
    try:
        df = pd.read_excel(full_path)
        # df['日期'] = pd.to_datetime(df['日期'], errors='coerce')
        df['日期'] = df['日期'].astype(str).str[:10]
        df['日期'] = pd.to_datetime(df['日期'], format="%Y-%m-%d", errors='coerce')

        df['month'] = df['日期'].dt.month
        df['year'] = df['日期'].dt.year

        df = df[df['year'].isin([2020, 2021, 2022, 2023, 2024, 2025])]
        df['最高温'] = df['最高温'].astype(str).str.extract(r"(-?\d+)").astype(float)
        df['最低温'] = df['最低温'].astype(str).str.extract(r"(-?\d+)").astype(float)

        df['平均温'] = (df['最高温'] + df['最低温']) / 2

        summer_temp = df[df['month'].isin([6, 7, 8])]['平均温'].mean()
        winter_temp = df[df['month'].isin([12, 1, 2])]['平均温'].mean()

        summer_avg.append(round(summer_temp, 2))
        winter_avg.append(round(winter_temp, 2))
    except Exception as e:
        summer_avg.append(None)
        winter_avg.append(None)

# 构建图表
bar = (
    Bar(init_opts=opts.InitOpts(width="1000px", height="500px"))
    .add_xaxis(districts)
    .add_yaxis("夏季平均气温", summer_avg)
    .add_yaxis("冬季平均气温", winter_avg)
    .set_series_opts(label_opts=opts.LabelOpts(is_show=True))
    .set_global_opts(
        title_opts=opts.TitleOpts(pos_left="center", pos_top="10px"),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=30)),
        yaxis_opts=opts.AxisOpts(name="温度（℃）"),
        legend_opts=opts.LegendOpts(pos_bottom="bottom")
    )
)
# title="2020–2025年北京各区夏冬季平均气温比较",
output_path = "heat_island_effect.html"
bar.render(output_path)
webbrowser.open(output_path)
